<?php
namespace App\Http\Controllers;

use App\Http\Library\UserAuth;
use App\Http\Library\WeChat\MiniWeChat;
use App\Http\Response\ApiResponse;
use App\Models\User;
use App\Models\Worker;
use Closure;
use Exception;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;


/**
 * 前端Api基类
 * Class ApiController
 * @package App\Common\Controllers
 */
class ApiController extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    /**
     * 登陆用户
     * @var null|UserAuth
     */
    protected ?UserAuth $auth = null;

    /**
     * 当前请求
     * @var Request|null
     */
    protected ?Request $request = null;

    protected ?User $user = null;
    protected int $user_id = 0;
    protected int $shop_id = 0;
    protected int $worker_id = 0;


    public function __construct(Request $request, UserAuth $userAuth)
    {
        $this->request = $request;
        $this->auth = $userAuth;

        $this->user = auth('sanctum')->user();
        if ($this->user){
            $this->user_id = $this->user->id;
            $worker = $this->user->worker;
            if ($worker){
                $this->worker_id = $worker->id;
                $this->shop_id = $worker->shop_id;
            }
            if ($this->user->status==1){
                admin_error("此账号已被禁用,请联系管理员！");
            }
        }
    }

    protected function getUserInfo($id = 0){
        $id = $id?:$this->user_id;
        return $this->auth->getUserInfo($id);
    }

    /**
     * @param callable $callback
     * @param string|null $out_trade_no 订单编号
     * @return ApiResponse|mixed
     */
    public function wechatPay(callable $callback, string $out_trade_no = null){
        $out_trade_no = $out_trade_no?:build_order_no();
        DB::beginTransaction();
        $wechat = MiniWeChat::instance();
        $openid = $this->user->openid;
        $user_id = $this->user_id;
        try {
            $payData = $callback($out_trade_no,$openid,$user_id);
            if (isset($payData['response'])){
                $res = $payData;
            }else{
                $res = $wechat->pay($payData);
            }
            Log::error(json_encode($res,JSON_UNESCAPED_UNICODE));
            DB::commit();
        }catch (QueryException|Exception $e){
            DB::rollBack();
            return $this->response()->error($e->getMessage());
        }
        if($res!==false){
            if (isset($res['response'])){
                return $res['response'];
            }
            if ($res['return_code']==='SUCCESS'&&$res['result_code']==='SUCCESS'){
                $jssdk = $wechat->getPayJsSdk($res['prepay_id']);
                return $this->response()->success('支付SDK信息')->data(['payInfo'=>$jssdk,'order_id'=>$out_trade_no]);
            }else{
                $msg = $res['return_msg']?:'下单失败,请重新支付!';
                $msg = $msg=='OK'?$res['err_code_des']:$msg;
                return $this->response()->error($msg);
            }
        }else{
            return $this->response()->error("下单失败,请重新支付!");
        }
    }

    public function response(): ApiResponse
    {
        return new ApiResponse();
    }


    /**
     * @param Closure $callback
     * @return ApiResponse
     */
    public function tryCatch(Closure $callback): ApiResponse
    {
        try {
            return $callback();
        } catch (Exception|Throwable $e) {
            return $this->response()->error($e->getMessage());
        }
    }
}
